package com.example.ktapplication.model

import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.elvishew.xlog.XLog
import com.example.ktapplication.AppGlobals
import com.example.ktapplication.bean.LoginBean
import com.example.ktapplication.bean.RegisterBean
import com.example.ktapplication.state.LoginState
import com.example.ktapplication.state.RegisterState
import com.example.ktapplication.utils.NetworkUtils
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.catch
import kotlinx.coroutines.flow.distinctUntilChangedBy
import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.flow.flowOn
import kotlinx.coroutines.launch
import com.example.ktapplication.net.NetRepository

class RegisterViewModel: ViewModel() {

    private var _state = MutableStateFlow<RegisterState>(RegisterState.OnSuccess(null))
    var state: StateFlow<RegisterState> = _state

   lateinit var mUserName:String
   lateinit var mPwd:String
   lateinit var mPwd2:String

    fun register(userName:String,pwd:String,pwd2:String) {
        mUserName=userName
        mPwd=pwd
        mPwd2=pwd2
        XLog.d("======第一次请求会发送数据===1====")
        viewModelScope.launch {
            register.flowOn(Dispatchers.IO)
                .catch { exception ->
                    _state.value = RegisterState.OnError(exception)
                }
                .collect { data ->
                    XLog.d("======第一次请求会发送数据===3====")
                    _state.value = RegisterState.OnSuccess(data)
                }
        }
    }

    private val register: Flow<RegisterBean> = flow {
        if (!NetworkUtils.isConnected(AppGlobals.getApplication())){
            throw RuntimeException("网络未连接")
        }
        XLog.d("======第一次请求会发送数据===2====")
        //网络请求
        val data = NetRepository.instance.service.register(mUserName,mPwd,mPwd2)
        //返回结果
        emit(data)
    }

    override fun onCleared() {
        super.onCleared()
    }
}
